package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.activity.n.PurMapActivity;
import com.aoxon.cargo.bean.District;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.component.SideBar;
import com.aoxon.cargo.component.SideBar.OnTouchingLetterChangedListener;
import com.aoxon.cargo.component.WordScrollView;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.GetCityService;
import com.aoxon.cargo.service.GetMarketService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.SearchSupplierTipsService;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.google.gson.reflect.TypeToken;

public class PurSupplierSearch2Activity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {
	private ImageView ivReturnButton;
	private ImageView ivGPSButton;
	private TextView tvTitle;

	private EditText etSearchText;

	private LinearLayout llSearchSupTip;
	private LinearLayout llCity, llMarket;
	private SideBar sideBar;
	private WordScrollView svCity, svMarket;

	private int loadType = 0;
	private final int GET_TIPS = 0;
	private final int GET_CITYS = 1;
	private final int GET_MARKET = 2;
	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private String strSearchText = new String();
	private String cityString = new String();

	private List<String> tips = new ArrayList<String>();
	private List<District> cityDistricts = new ArrayList<District>();
	private List<District> marketDistricts = new ArrayList<District>();

	private int width;

	private SearchSupplierTipsService searchSupplierTipsService = (SearchSupplierTipsService) MyServiceFactory
			.getInstance(MyServiceFactory.SEARCH_SUPPLIER_TIPS);
	private GetCityService getCityService = (GetCityService) MyServiceFactory
			.getInstance(MyServiceFactory.GET_CITY);
	private GetMarketService getMarketService = (GetMarketService) MyServiceFactory
			.getInstance(MyServiceFactory.GET_MARKET);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）
		setup();
	}

	private void setup() {
		setContentView(R.layout.sup_search_sup);

		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivGPSButton = (ImageView) findViewById(R.id.ivPublicTitleOther);
		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);

		etSearchText = (EditText) findViewById(R.id.etPublicSearchText);

		llSearchSupTip = (LinearLayout) findViewById(R.id.llTips_search_sup);
		llCity = (LinearLayout) findViewById(R.id.llCity_search_sup);
		llMarket = (LinearLayout) findViewById(R.id.llMarket_search_sup);
		svCity = (WordScrollView) findViewById(R.id.svCity_search_sup);
		svMarket = (WordScrollView) findViewById(R.id.svMarket_search_sup);
		sideBar = (SideBar) findViewById(R.id.sideBar_search_sup);

		ivGPSButton.setImageResource(R.drawable.button_gps);
		tvTitle.setText("选择商圈");
		etSearchText.setHint(" 请输入商圈名称");
		sideBar.setOnTouchingLetterChangedListener(sideBarTouch);
		normalDataLoader.setOnloadDataListener(this);
		ivReturnButton.setOnClickListener(onClick);
		ivGPSButton.setOnClickListener(onClick);
		etSearchText.addTextChangedListener(myTextWatcher);
		svCity.setShowHot(true);

		loadType = GET_CITYS;
		normalDataLoader.load();
	}

	OnClickListener onClick = new OnClickListener() {
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.ivPublicTitleReturn:
				PurSupplierSearch2Activity.this.finish();
				break;
			case R.id.ivPublicTitleOther:
				PurMapActivity.LAUNCH_MODE = PurMapActivity.MY_LOC_AND_SUPLIST;
				Intent intent = new Intent(PurSupplierSearch2Activity.this,
						PurMapActivity.class);
				startActivity(intent);
				break;
			}
		};
	};

	OnClickListener cityOnClick = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			// Log.v(tag, msg)
			Resources rs = PurSupplierSearch2Activity.this.getResources();
			TextView tv;

			View onClickViewBefore = svCity.onClickedView;
			if(onClickViewBefore != null){
				onClickViewBefore.setBackgroundColor(rs.getColor(R.color.white));
				tv = (TextView) (onClickViewBefore
						.findViewById(R.id.tvItem_search_sup));
				tv.setTextColor(rs.getColor(R.color.black));
			}

			District dis = (District) view.getTag();
			Log.v("item onclick", dis.getDistrict());
			view.setBackgroundColor(rs.getColor(R.color.blue));
			svCity.onClickedView = view;
			tv = (TextView) (view.findViewById(R.id.tvItem_search_sup));
			tv.setTextColor(rs.getColor(R.color.white));
			cityString = dis.getDistrict();
			loadType = GET_MARKET;
			normalDataLoader.load();
		}
	};

	OnClickListener marketOnClick = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			String strMarket;
			strMarket = ((District) view.getTag()).getDistrict();
			Intent intent = new Intent(getBaseContext(),
					PurSupplierSearchShowActivity.class);
			intent.putExtra("city", cityString);
			intent.putExtra("market", strMarket);
			intent.putExtra("searchFormText", false);
			startActivity(intent);
		}
	};

	OnTouchingLetterChangedListener sideBarTouch = new OnTouchingLetterChangedListener() {

		@Override
		public void onTouchingLetterChanged(String s) {
			// TODO Auto-generated method stub
			svCity.scrollToWord(s);
		}

	};

	private void showMarket() {
		svMarket.setItemOnClick(marketOnClick);
		svMarket.setUp(marketDistricts, llMarket);
		FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) svCity
				.getLayoutParams();
		params.width = (int) (width * (2 / 5.0));
		svCity.setLayoutParams(params);

		FrameLayout.LayoutParams marketParams = (FrameLayout.LayoutParams) svMarket
				.getLayoutParams();
		marketParams.width = (int) (width * (3 / 5.0));
		svMarket.setLayoutParams(marketParams);
		svMarket.setVisibility(View.VISIBLE);

	}

	TextWatcher myTextWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			llSearchSupTip.removeAllViews();
			strSearchText = etSearchText.getText().toString();
			if (strSearchText != null && !strSearchText.equals("")) {
				tips.clear();
				tips.add(strSearchText);
				loadType = GET_TIPS;
				normalDataLoader.load();
			}
		}
	};

	/**
	 * 显示搜索提示
	 */
	private void showTip() {
		for (int i = 0; i < tips.size(); i++) {
			final String tip = tips.get(i);
			View tipItem = getLayoutInflater().inflate(
					R.layout.pur_search_tip_text, null);
			TextView textView = (TextView) tipItem
					.findViewById(R.id.tvPurSearchGoodsTip);
			textView.setText(tip);

			tipItem.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getBaseContext(),
							PurSupplierSearchShowActivity.class);
					Bundle data = new Bundle();
					data.putBoolean("searchFormText", true);
					data.putString("searchText", tip);
					intent.putExtras(data);
					startActivity(intent);
				}
			});

			llSearchSupTip.addView(tipItem);

		}
	}

	// 将newList按首字母从小到大排好序插入到addList
	private void sortWord(List<District> newList, List<District> addList) {
		int mini = 0;
		char newChar1, newChar2;
		for (int i = 0; newList.size() > 0;) {
			mini = 0;
			newChar1 = newList.get(i).getFirstLetter().charAt(0);
			for (int j = 1; j < newList.size(); j++) {
				newChar2 = newList.get(j).getFirstLetter().charAt(0);
				if (newChar1 > newChar2) {
					newChar1 = newChar2;
					mini = j;
				}
			}
			addList.add(newList.get(mini));
			newList.remove(mini);
		}
	}

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub

	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		GsonBean gsonBean = null;
		switch (loadType) {
		case GET_TIPS:
			gsonBean = searchSupplierTipsService.execute(0, 10, strSearchText);
			if (CheckStateUtil.check(gsonBean)) {
				List<String> tipList = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<String>>() {
						}.getType());
				tips.addAll(tipList);
			}
			msg.what = MyStateUtil.SEARCH_TIP_SHOW;
			break;
		case GET_CITYS:
			if (cityDistricts.size() % 100 != 0) {
				cityDistricts.clear();
			}
			gsonBean = getCityService.execute(0, 100);
			if (CheckStateUtil.check(gsonBean)) {
				List<District> districts = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<District>>() {
						}.getType());
				sortWord(districts, cityDistricts);
				// cityDistricts.addAll(districts);

			}
			msg.what = MyStateUtil.SEARCH_CITY_SHOW;
			break;
		case GET_MARKET:
			if (marketDistricts.size() % 100 != 0) {
				marketDistricts.clear();
			}
			gsonBean = getMarketService.execute(cityString, 0, 100);
			if (CheckStateUtil.check(gsonBean)) {
				List<District> districts = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<District>>() {
						}.getType());
				sortWord(districts, marketDistricts);
				// marketDistricts.addAll(districts);

			}
			msg.what = MyStateUtil.SEARCH_MARKET_SHOW;
			break;
		default:
			break;
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		llSearchSupTip.removeAllViews();
		switch (state) {
		case MyStateUtil.SEARCH_TIP_SHOW:
			llSearchSupTip.setVisibility(View.VISIBLE);
			showTip();
			break;
		case MyStateUtil.SEARCH_CITY_SHOW:
			Log.v("citys", DataUtil.gson.toJson(cityDistricts));
			svCity.setItemOnClick(cityOnClick);
			svCity.setUp(cityDistricts, llCity);
			// llSearchSupCity.setVisibility(View.VISIBLE);
			// showCity();
			break;
		case MyStateUtil.SEARCH_MARKET_SHOW:
			showMarket();
			// svMarket.setUp(marketDistricts, llMarket);
			// svMarket.setVisibility(View.VISIBLE);
			// LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
			// etSearchText
			// .getLayoutParams();
			// params.width = width - DisplayUtil.dip2px(this, 78);
			// svMarket.set
			break;
		default:
			break;
		}
	}
}
